<?php
namespace app\services;

use app\models\User;

class BrandService extends UsersService {
    public $matrix = [
        'id' => 'id',
        'name' => 'name',
        'largeVocation' => 'parent_category',
        'mediumVocation' => 'child_category',
        'transformName' => 'convertion_name',
        'transformBelongMethod' => ['conversion_vest_method', 
                                    '$v==1 && $tip="最后一次点击";
                                     $v==2 && $tip="最后一次曝光";
                                     $v==3 && $tip="最后一次曝光和点击";
                                     return $tip; '],
        'lastModifiedDate' => 'last_update',
        'operate' => ['id', 'return "edit";'],
    ];

    public function setRef() {
        return $this->getOperatorsAndAgent();
    }

    public function addNewAdvertiser($data, $isApi = false, $userId = 0) {
        if (!$isApi) {
            $categoryId = $this->getAdvertiserCategory($data['parent_category'], $data['category']);
            $data['category_id'] = $categoryId;
        }
        $ad = $this->saveData('Advertiser', $data);
        if (is_array($ad) && $ad['id']) {
            $saveKey['resource_type'] = 2;//advertiser
            $saveKey['resource_id'] = $ad['id'];
            $users = [];
            if (!$isApi) {
                $this->update('UserResource', $saveKey);
                isset($data['bind_users']) && $users = $data['bind_users'];
                $this->S('user_rank') != 'root' && $users[] = $this->S('user_id');
            } else {
                $users = [$userId];
            }
            if ($users) {
                foreach ($users as $id) {
                    $resource['user_id'] = $id;
                    $saveKey =  array_merge($saveKey, $resource);
                    $resource = array_merge($saveKey, $resource, ['status' => 1]); 
                    $this->saveOn('UserResource', $saveKey, $resource);
                }
            }

            // 一旦广告主新添加成功，则需要刷新当前可选广告主列表
            if (!$isApi) {
                $us = new UsersService();
                $us->freshSession();
            }
            return [true, $ad];
        }
        return [false, []];
    }

    public function getAdvertiserCategory($parent, $child) {
        $adnetworkId = $this->S('ad_network_id');
        $service = new \app\services\CreativeService();
        return $service->getCreativeCategoryId($parent, $child);
    }

    /**
     * 获取运营人员名单， root 默认具有所有权限
     */
    public function getOperatorsAndAgent() {
        $allUsers = $this->getAll('User', 'user_type in (2, 3, 4)');
        if ($this->S('user_rank') == 'root') return $allUsers;

        $bindUsers = $this->getAll('UserResource', ['user_id'=>$this->S('user_id'), 'resource_type' => 1, 'status' => 1]);
        if (!$bindUsers)  return [];
        $userIds = array_column($allUsers, 'id');
        $bindIds = array_column($bindUsers, 'resource_id');
        $bindIds = array_intersect($bindIds,  $userIds);
        $where = 'id in ('.implode(',', $bindIds). ')';
        return $this->getAll('User', $where);
    }

    public function getAllAdvertisers() {
        $service = new UsersService();
        $user = $this->M('User', $this->S('user_id'));
        $datas = $service->getUserAdvertisers($user, 2, false);
        //$datas = $this->getAll('Advertiser', []);
        $adnetworkId = $this->S('ad_network_id');
        $service = new \app\services\CreativeService();
        foreach ($datas as &$data) {
            // 其他
            if (!$data['category_id']) {
                $data['category_id'] = 99;
            }
            $cates = $service->getCategorieById($data['category_id']);
            $cates = $cates['tags'];
            $cates = explode(', ', $cates);
            $data['parent_category'] = array_shift($cates);
            $data['child_category'] = '';
            if (!empty($cates)) {
                $data['child_category'] = array_pop($cates);
            }
        }
        return $this->fieldsMap($this->matrix, $datas);
    }
}// end of advertiser service declaration
